#include "maindialog.h"
#include "ui_maindialog.h"

#include <QTcpSocket>

mainDialog::mainDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::mainDialog)
{
    ui->setupUi(this);

    m_sock = new QTcpSocket(this);

    connect(m_sock, &QTcpSocket::connected, this, mainDialog::connectSuccess);
    connect(m_sock, &QTcpSocket::errorOccurred, this, mainDialog::connectFail);
    connect(m_sock, &QTcpSocket::readyRead, this, &mainDialog::recvMsg);

    ui->edtRecord->appendPlainText("[系统]正在连接服务器");
    ui->btnSend->setEnabled(false);

    m_sock->connectToHost("120.55.42.163", 8879);
}

mainDialog::~mainDialog()
{
    delete ui;
}

void mainDialog::connectSuccess()
{
    ui->edtRecord->appendPlainText("[系统]连接服务器成功");
    ui->btnSend->setEnabled(true);
}

void mainDialog::connectFail()
{
    ui->edtRecord->appendPlainText("[系统]连接服务器失败");
    ui->btnSend->setEnabled(false);
}

void mainDialog::recvMsg()
{
    QByteArray data = m_sock->readAll();

    ui->edtRecord->appendPlainText("<--  " + QString(data));
}

void mainDialog::on_btnSend_clicked()
{
    QString data = ui->edtMsg->toPlainText();
    if(!data.isEmpty())
    {
        m_sock->write(data.toUtf8());
        ui->edtRecord->appendPlainText("-->  " + data);
        ui->edtMsg->clear();
    }
}

